# -*- encoding: utf-8 -*-

import os.path
from django.template import loader, TemplateDoesNotExist
from django.http import HttpResponse
from django.shortcuts import render_to_response

class DefaultView(object):
    '''Default functions for Bookmarks'''
    
    def __init__(self, request):
        self.request = request
        self.method = request.POST
        self.user = request.user
        self.redir = ('redir' in request.GET) and request.GET['redir'] or False

    def xml_printer(self, *args, **kwargs):
        '''Returns text/xml Content-type at render_to_response'''
        renderer = HttpResponse(loader.render_to_string(*args, **kwargs))
        renderer.headers['Content-Type'] = 'text/xml; charset=utf-8'
        return renderer

    def error_message(self, fields=[], msg=''):
        '''Returns error messages to default error template'''
        try:
            return self.xml_printer('default/error.xml', {'fields':fields, 'msg':msg})
        except TemplateDoesNotExist:
            return self.xml_printer('default\error.xml', {'fields':fields, 'msg':msg})

    def success_message(self, function, value=False):
        '''Returns successfull message to default success template'''
        try:
            return self.xml_printer('default/success.xml', {'function':function, 'value':value})
        except:
            return self.xml_printer('default\success.xml', {'function':function, 'value':value})

      
        
    def treat(self, value):
        '''Return value treated'''
        #
        # TODO: Treat string, to take off special characters, and replace html content and char entity
        #
        return value
        
def render_template(request, template='index.html'):
    """Renders default templates"""
    # Set default template as index.html
    if template.strip() == '':
        template = 'index.html'
    # Remove / from end of file
    if template.endswith('/'):
        template = template[:-1]
    
    # Add extension to file
    if not template.endswith('.html'):
        template += '.html'

    # Get path of file
    path = str(request.path)[1:str(request.path)[1:].find('/')+1]
    # Concat template with filename
    template = os.path.sep.join((path, template))
    
    try:
        return render_to_response(template, {})
    except TemplateDoesNotExist:
        return render_to_response('default/404.html', {})


